package com.chenshu.shop.service;

import com.chenshu.shop.mapper.CartMapper;
import com.chenshu.shop.model.Cart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-12
 * Time：16:59
 */
@Service
@Slf4j
public class CartService {
    @Autowired
    CartMapper cartMapper;
    public boolean buyCart(Integer userId, Integer goodId) {
        Cart cart = cartMapper.checkCart(userId, goodId);
        if (cart == null) {
            Integer row = cartMapper.insertCart(userId, goodId);
            if (row == 1) {
                log.info("新增购物车成功");
                return true;
            } else {
                log.info("新增购物车失败");
                return false;
            }
        } else {
            Integer row = cartMapper.updateCart(userId, goodId);
            if (row == 1) {
                log.info("购物车商品数量增加成功");
                return true;
            } else {
                log.info("购物车商品数量增加失败");
                return false;
            }
        }
    }

    public List<Cart> getCartsByUid(Integer userId) {
        List<Cart> cartList = cartMapper.selectCardsByUid(userId);
        for (Cart cart : cartList){
            cart.setTotal(cart.getAmount() * cart.getGood().getPrice());
        }
        return cartList;
    }

    public void addCart(Integer id) {
        Integer row = cartMapper.addCart(id);
        if (row == 1) {
            log.info("购物车商品数量增加成功");
        } else {
            log.info("购物车商品数量增加失败");
        }
    }

    public void decreaseCart(Integer id) {
        Integer row = cartMapper.lessCart(id);
        if (row == 1) {
            log.info("购物车商品数量减少成功");
        } else {
            log.info("购物车商品数量减少失败");
        }
    }

    public void deleteCart(Integer id) {
        Integer row = cartMapper.deleteCart(id);
        if (row == 1) {
            log.info("删除购物车商品成功");
        } else {
            log.info("删除购物车商品失败");
        }
    }

    public Integer cartCount(Integer uid) {
        return cartMapper.selectCardsCount(uid);
    }
}
